/*****************************************
  NAME: buzzer.c
  DESC: buzzer test
  WWW.YCTEK.COM
 *****************************************/

#include "def.h"
#include "option.h"
#include "2410addr.h"
#include "2410lib.h"
#include "2410slib.h" 

#include <stdarg.h>
#include <string.h>
#include <stdlib.h>

#include <ctype.h>
#include "buzzer.h"
#define ESC_KEY	0x1b
void Buzzer_Freq_Set( U32 freq )
{
	rGPBCON &= ~12;			//set GPB1 as tout1, pwm output
	rGPBCON |= 8;
		
	rTCFG0 &= ~0xff;
	rTCFG0 |= 15;			//prescaler = 15+1
	rTCFG1 &= ~0xf;
	rTCFG1 |= 2;			//mux = 1/8
	rTCNTB1 = (PCLK>>7)/freq;
	rTCMPB1 = rTCNTB1>>1;	// 50%
	rTCON &= ~0xf10;
	rTCON |= 0xb00;			//disable deadzone, auto-reload, inv-off, update TCNTB1&TCMPB1, start timer 1
	rTCON &= ~0x200;			//clear manual update bit
}

void Buzzer_Stop( void )
{
	rGPBCON &= ~12;
	rGPBCON |= 4;
	rGPBDAT |= 2;
}


void BUZZER_PWM_Test( void )
{
	U16 freq = 2000 ;
	
	Uart_Printf( "\nBUZZER TEST ( PWM Control )\n" );
   	Uart_Printf( "Press +/- to increase/reduce the frequency of BUZZER !\n" ) ;
	Uart_Printf( "Press 'ESC' key to Exit this program !\n\n" );
	
	Buzzer_Freq_Set( freq ) ;

    while( 1 )
    {
		U8 key = Uart_Getch();

		if( key == '+' )
		{
			if( freq < 20000 )
				freq += 100 ;
				
			Buzzer_Freq_Set( freq ) ;
		}

		if( key == '-' )
		{
			if( freq > 100 )
				freq -= 100 ;
				
			Buzzer_Freq_Set( freq ) ;
		}
		
		Uart_Printf( "\tFreq = %d\n", freq ) ;
		if( key == ESC_KEY )
		{
			Buzzer_Stop() ;
			return ;
		}
	}
}
